package main

import (
	"encoding/json"
	"fmt"
	"github.com/go-resty/resty/v2"
	"log"
	"strconv"
	"sync"
	gconf2 "yundian/cmd/tools/grawl/gconf"
	"yundian/internel/app/models/dividendslog"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/wechatpay"
)

func main()  {
	dingo.InitViper("./configs/admin.yaml")
	dbs.NewMysqlComponent().Step()

	var wg sync.WaitGroup
	var lock sync.Mutex
	// 100000  100067
	// 100001 - 100066
	// 100068 - 100100
	// 100101 - 100200
	// 100201 - 100300
	// 100301 - 100400
	// 100401 - 100500
	// 100501 - 100600
	// 100601 - 100700
	// 100701 - 100915
	for i := 100000; i<= 100000; i++ {
		wg.Add(1)
		go func(i int) {
			lock.Lock()
			defer wg.Done()
			dividendsLog(i)
			lock.Unlock()
		}(i)
	}
	wg.Wait()
}

// 抓取每个代理商的结算日志
func dividendsLog(id int)  {
	userId := strconv.Itoa(id)
	um := users.New()
	global.Orm.Table("users").Where("id = ?", id).Find(um)

	if um.DeviceCount > 0 {
		log.Println("用户-",um.Name,"拥有",um.DeviceCount,"条设备")
		// 抓取
		url := "http://mng.yundian.ink/mng/10041/user/agent/settlement/orderItem/list.data"
		client := resty.New()
		// 先取一页，看下总数是多少条
		m := map[string]string{}
		m["page"] = strconv.Itoa(1)
		m["limit"] = strconv.Itoa(10)
		m["userId"] = userId  // 用户ID
		resp, err := client.R().
			SetHeader("Content-Type", "application/x-www-form-urlencoded").
			SetFormData(m).
			SetHeader("Cookie", gconf2.Cookie).
			//SetResult(placeType).    // or SetResult(AuthSuccess{}).
			Post(url)
		if err != nil {
			log.Println("抓取失败")
		}
		b := resp.Body()
		sett := &SettLogGenerated{}
		_ = json.Unmarshal(b, sett)

		pageSize := 3000
		pages := 1
		if sett.Body.Total > 0 {
			// 计算分页
			pages = (sett.Body.Total - 1)/pageSize + 1
		}
		log.Println("测试打印数据------pages", pages)
		if len(sett.Body.Data) > 0 {
			for i := 1; i <= pages; i++ {
				m := map[string]string{}
				m["page"] = strconv.Itoa(i)
				m["limit"] = strconv.Itoa(pageSize)
				m["userId"] = userId  // 用户ID
				resp, err := client.R().
					SetHeader("Content-Type", "application/x-www-form-urlencoded").
					SetFormData(m).
					SetHeader("Cookie", gconf2.Cookie).
					//SetResult(placeType).    // or SetResult(AuthSuccess{}).
					Post(url)
				if err != nil {
					log.Println("抓取失败")
				}

				body := resp.Body()
				lists := new(SettLogGenerated)
				_ = json.Unmarshal(body, lists)
				var ccount,ucount int
				for _,lst := range lists.Body.Data {
					orderInfo := orders.New()
					global.Orm.Table("orders").Where("trade_no = ?",lst.TradeNo).Find(orderInfo)

					m := dividendslog.New()
					m.Id = lst.ID
					m.TradeNo = lst.TradeNo

					m.Money = int64(lst.Money)
					m.MoneyStr = lst.MoneyStr
					m.PayMoney = orderInfo.PayMoney
					m.PayMoneyStr = orderInfo.PayMoneyStr
					m.SettlementMoney = int64(lst.SettlementMoney)
					m.SettlementMoneyStr = lst.SettlementMoneyStr

					m.ProfitType = int8(lst.ProfitType)
					m.ProfitProportion = int8(lst.ProfitProportion)

					m.DeviceSn = lst.DeviceSn
					m.SharedMode = lst.SharedMode
					m.FeeMode = int8(lst.FeeMode)
					m.DeviceTypeID = lst.DeviceTypeID
					m.DeviceTypeName = lst.DeviceTypeName

					m.UserId = lst.UserID
					m.UserName = lst.UserName
					m.PlaceId = lst.PlaceID
					m.PlaceName = lst.PlaceName
					m.MemberId = orderInfo.MemberId
					m.MemberName = orderInfo.MemberName

					m.State = int8(lst.State)

					m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
					m.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))


					var count int64
					global.Orm.Table("dividends_log").Where("id = ?", lst.ID).Count(&count)
					if count > 0 {
						ucount++
						global.Orm.Table("dividends_log").Where("id = ?", lst.ID).Model(&m).Updates(m)
					} else {
						ccount++
						global.Orm.Table("dividends_log").Create(m)  //新增
					}
				}
				fmt.Printf("用户:%s(%s)当前页-%d,新增%d条,更新%d条 \n",um.Name,userId,i,ccount,ucount)
			}
		}

	} else {
		log.Println("-----------用户-",um.Name,"拥有",um.DeviceCount,"条设备--------------")
	}

}

type SettLogGenerated struct {
	Code int `json:"code"`
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			ID                 int    `json:"id"`
			TradeNo            string `json:"tradeNo"`
			UserID             int    `json:"userId"`
			UserName           string `json:"userName"`
			PlaceID            int    `json:"placeId"`
			PlaceName          string `json:"placeName"`
			DeviceSn           string `json:"deviceSn"`
			SharedMode         string `json:"sharedMode"`
			FeeMode            int    `json:"feeMode"`
			DeviceTypeID       int    `json:"deviceTypeId"`
			DeviceTypeName     string `json:"deviceTypeName"`
			RoleType           int    `json:"roleType"`
			ProfitType         int    `json:"profitType"`
			ProfitProportion   int    `json:"profitProportion"`
			Money              int    `json:"money"`
			SettlementMoney    int    `json:"settlementMoney"`
			State              int    `json:"state"`
			UpdateDate         string `json:"updateDate"`
			CreateDate         string `json:"createDate"`
			MoneyStr           string `json:"moneyStr"`
			ProfitTypeName     string `json:"profitTypeName"`
			SettlementMoneyStr string `json:"settlementMoneyStr"`
			WalletType         int    `json:"walletType"`
			RoleTypeName       string `json:"roleTypeName"`
		} `json:"data"`
	} `json:"body"`
}


